package com.bigtotoro.shuiyincamera.video;

import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.helper.ItemTouchHelper;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.Toast;
import android.widget.VideoView;

import com.bigtotoro.shuiyincamera.R;
import com.bigtotoro.shuiyincamera.adapter.OnItemChildClickListener;
import com.bigtotoro.shuiyincamera.adapter.SimpleAdapter3;
import com.bigtotoro.shuiyincamera.adapter_can_moved.ItemDragHelperCallback;
import com.bigtotoro.shuiyincamera.editimage.utils.CompatResourceUtils;
import com.bigtotoro.shuiyincamera.editimage.utils.FileUtil;
import com.bigtotoro.shuiyincamera.editimage.view.SpaceItemDecoration;
import com.bigtotoro.shuiyincamera.ShowMyArtsActivity;
import com.bigtotoro.shuiyincamera.image.RemoveWaterMarkActivity;
import com.bigtotoro.shuiyincamera.model.ColorEntity;
import com.bigtotoro.shuiyincamera.model.MyArt;
import com.bigtotoro.shuiyincamera.util.ModelSingle;
import com.bigtotoro.shuiyincamera.util.MyUtils;
import com.bigtotoro.shuiyincamera.util.VideoUtil;
import com.bigtotoro.shuiyincamera.video.trim.VideoTrimmerActivity;
import com.luck.picture.lib.entity.LocalMedia;
import com.umeng.analytics.MobclickAgent;

import java.util.ArrayList;
import java.util.List;

import de.hdodenhof.circleimageview.CircleImageView;
import qiu.niorgai.StatusBarCompat;

import static com.bigtotoro.shuiyincamera.editimage.Constacts.EXTRA_OUTPUT;

//视频拼接

public class VideoSpliceActivity extends AppCompatActivity implements View.OnClickListener {
    public static final String TAG = "main";
    private FrameLayout frameLayout;
    private VideoView videoView;

    int frameWidth, frameHeight;
    int videoWidth, videoHeight, videoRotation, videoDuration;
    //    private String path = "/storage/emulated/0/dakashuiyin/video/slice/1553506380742.mp4"; // 3s
    private String path1 = ""; // 3s
    private String path2 = ""; // 3s
    private String out;
    private float scale;
    private float videoX, videoY;
    private ProgressDialog mProgressDialog;

    private List<LocalMedia> selectList7;
    private MediaPlayer.OnPreparedListener OnPreparedListener = new MediaPlayer.OnPreparedListener() {
        @Override
        public void onPrepared(MediaPlayer mediaPlayer) {
            videoWidth = mediaPlayer.getVideoWidth();
            videoHeight = mediaPlayer.getVideoHeight();
            videoDuration = mediaPlayer.getDuration();
            Log.d("main", "setOnPreparedListener duration " + videoDuration);

            videoView.start();
            //根据列表循环播放
//            mediaPlayer.setLooping(true); //循环播放

            frameWidth = frameLayout.getWidth();
            frameHeight = frameLayout.getHeight();
            Log.d(TAG, "frame" + frameWidth + ":" + frameHeight);
            Log.d(TAG, "video" + videoWidth + ":" + videoHeight);
//                Toast.makeText(MainActivity.this, frameWidth+":"+frameHeight, Toast.LENGTH_SHORT).show();

            //Get VideoView's current width and height
            int videoViewWidth = videoView.getWidth();
            int videoViewHeight = videoView.getHeight();

            float xScale = (float) videoViewWidth / videoWidth;
            float yScale = (float) videoViewHeight / videoHeight;

            //For Center Crop use the Math.max to calculate the scale
            //float scale = Math.max(xScale, yScale);
            //For Center Inside use the Math.min scale.
            //I prefer Center Inside so I am using Math.min
            scale = Math.min(xScale, yScale);

            float scaledWidth = scale * videoWidth;
            float scaledHeight = scale * videoHeight;

            //Set the new size for the VideoView based on the dimensions of the video
            ViewGroup.LayoutParams layoutParams = videoView.getLayoutParams();
            layoutParams.width = (int) scaledWidth;
            layoutParams.height = (int) scaledHeight;
            videoView.setLayoutParams(layoutParams);

            videoView.invalidate();
            videoX = (frameWidth - layoutParams.width) / 2;
            videoY = (frameHeight - layoutParams.height) / 2;

            Log.d(TAG, "scaledWidth " + scaledWidth + " scaledHeight " + scaledHeight);
            Log.d(TAG, "video after set params");
            Log.d(TAG, "videoView" + videoView.getWidth() + ":" + videoView.getHeight());
            Log.d(TAG, "videoView getx " + videoView.getX() + " and getY " + videoView.getY());
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_video_splice);
        StatusBarCompat.setStatusBarColor(this, getResources().getColor(R.color.font_0));

//        path = getIntent().getStringExtra("path");
        videoView = findViewById(R.id.video);
        if (ModelSingle.getInstance().getMode2() != null) {
            selectList7 = (List<LocalMedia>) ModelSingle.getInstance().getMode2();
            //设置数据
            initRecycleView();
            if (recycleAdapter != null && selectList7 != null && selectList7.size() > 0) {
                dataList.clear();
                dataList.addAll(selectList7);
                recycleAdapter.setData(dataList);
                selectData.clear();
                selectData.add(selectList7.get(0));
                recycleAdapter.notifyDataSetChanged();

                setVideoView(dataList.get(0).getPath());

            }

        }
        path1 = getIntent().getStringExtra("path1");
        path2 = getIntent().getStringExtra("path2");
        findViewById(R.id.back).setOnClickListener(this);
        findViewById(R.id.btn_save).setOnClickListener(this);

        VideoUtil.checkVideoDir();
        frameLayout = findViewById(R.id.frame);


//        videoView.setVideoURI(Uri.parse(path));
//        setVideoView(selectData.get(0).getPath());
        videoView.setOnPreparedListener(OnPreparedListener);
    }

    private RecyclerView recyclerView;    //全部视频列表（按日期分类）
    private RecyclerView itemRecycleview;   //每个日期下的视频列表
    private List<LocalMedia> dataList = new ArrayList<>();
    private List<LocalMedia> selectData = new ArrayList<>();
    private SimpleAdapter3<LocalMedia> recycleAdapter = null;

    private int currentEditPosition;

    private void initRecycleView() {
        recyclerView = findViewById(R.id.recyclerView);

        LinearLayoutManager layoutManager = new LinearLayoutManager(VideoSpliceActivity.this);
        layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setNestedScrollingEnabled(false);  //防止recycleview和srcollview滑动冲突，必须加不然无法顺畅滑动列表
        recyclerView.addItemDecoration(new SpaceItemDecoration(
                CompatResourceUtils.getDimensionPixelSize(this, R.dimen.space_10),
                CompatResourceUtils.getDimensionPixelSize(this, R.dimen.space_0)
        ));
        recycleAdapter = new SimpleAdapter3<LocalMedia>(
                R.layout.item_recycle) {
            @Override
            public void onItemMove(int fromPosition, int toPosition) {
                Log.i("视频拼接","执行了recycleAdapter的 onItemMove方法");
                LocalMedia item1 = dataList.get(fromPosition);
                dataList.remove(fromPosition);
                dataList.add(toPosition, item1);
                notifyItemMoved(fromPosition, toPosition);


//                LocalMedia item01 = dataList.get(fromPosition);
//                LocalMedia item02 = dataList.get(toPosition);
//                dataList.set(toPosition, item01);
//                notifyItemChanged(toPosition);
////                if (toPosition < dataList.size()) {
////                    notifyItemRangeChanged(toPosition, dataList.size() - (toPosition));
////                }
//                dataList.set(fromPosition, item02);
//                notifyItemChanged(fromPosition);
//                notifyItemRangeChanged(fromPosition, dataList.size());

//                notifyDataSetChanged();
//                notifyItemRemoved(toPosition);
//                notifyItemRangeRemoved(toPosition,recycleAdapter.getItemCount());
//                notifyDataSetChanged();
            }

            @Override
            protected void onBindDataViewHolder(@NonNull BaseViewHolder holder, int position, LocalMedia localMedia) {

                if (selectData.contains(dataList.get(position))){
                    holder.findViewById(R.id.item).setSelected(true);
                }else {
                    holder.findViewById(R.id.item).setSelected(false);
                }

                View item = holder.findViewById(R.id.item);
                item.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        int position = (int) v.getTag();
                        LocalMedia local = dataList.get(position);



                        Toast.makeText(VideoSpliceActivity.this, ""+local.getCutPath(), Toast.LENGTH_SHORT).show();
                        //点击边框变黑
                        selectData.clear();
                        selectData.add(local);
                        recycleAdapter.notifyDataSetChanged();
                    }
                });
                item.setTag(holder.getAdapterPosition());

                CircleImageView iv_bg = holder.findViewById(R.id.iv_bg);
                iv_bg.setImageDrawable(getResources().getDrawable(R.drawable.default_img_edit));

                ImageView avatar = holder.findViewById(R.id.iv_photo);
                Bitmap bitmap = MyUtils.getVideoThumb(localMedia.getPath());
                if (localMedia != null && bitmap != null) {
                    avatar.setImageBitmap(bitmap);
                }

                View btn_edit = holder.findViewById(R.id.btn_edit);
                btn_edit.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        int position = (int) v.getTag();
                        currentEditPosition = position;
                        LocalMedia localMedia1 = dataList.get(position);
                        //点击进入视频剪切界面
                        startActivityForResult(new Intent(VideoSpliceActivity.this, VideoTrimmerActivity.class)
                                        .putExtra(VideoTrimmerActivity.VIDEO_PATH_KEY, localMedia1.getPath())
                                        .putExtra("mode", "splice_edit")
                                        .putExtra("position", position)
                                , REQUEST_CODE_SPLICE_EDIT
                        );
                        //剪切完毕需要替换掉原来的视频地址和参数
                    }
                });
                btn_edit.setTag(holder.getAdapterPosition());

            }
        };
        recycleAdapter.bindRecyclerView(recyclerView);

        //绑定长按拖拽,交换的实现逻辑放在了BaseHeaderFooterAdapter中
        ItemDragHelperCallback callback = new ItemDragHelperCallback(){
            @Override
            public boolean isLongPressDragEnabled() {
                // 长按拖拽打开
                return true;
            }
        };
        ItemTouchHelper helper = new ItemTouchHelper(callback);
        helper.attachToRecyclerView(recyclerView);
    }

    private String newpath = "";
    private static final int REQUEST_CODE_SPLICE_EDIT = 8399;

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent intent) {
        if (resultCode == RESULT_OK) {
            if (requestCode == REQUEST_CODE_SPLICE_EDIT) {
                if (intent != null && intent.getStringExtra("edit_path") != null) {
                    newpath = intent.getStringExtra("edit_path");
                    LocalMedia item = dataList.get(currentEditPosition);
                    item.setPath(newpath);
                    dataList.set(currentEditPosition, item);
                    recycleAdapter.notifyDataSetChanged();

                    setVideoView(dataList.get(0).getPath());

                }
            }
        }
    }

    private void setVideoView(String path) {

        videoView.pause();
        videoView.stopPlayback();
        videoView.setVideoURI(Uri.parse(path));
        videoView.start();
        videoView.setOnPreparedListener(OnPreparedListener);
    }


    @Override
    public void onClick(View view) {
        if (view.getId() == R.id.back) {
            finish();
        } else if (view.getId() == R.id.btn_save) {
//            RectF rect = cropView.getCropRect();
//            int x = (int) rect.left;
//            int y = (int) rect.top;
//            int width = (int) (rect.right-rect.left);
//            int height = (int) (rect.bottom-rect.top);
//            Log.d(TAG, x+","+y+"and "+width+"x"+height);
//            int trueX = (int) ((rect.left-videoView.getX())/scale);
//            int trueY = (int) ((rect.top-videoView.getY())/scale);
//            int trueWidth = (int) (width/scale);
//            int trueHeight = (int) (height/scale);
//            Log.d(TAG, trueX+","+trueY+"and "+width+"x"+height);

            //解决边界问题
//            trueX = trueX>0?trueX:1;
//            trueY = trueY>0?trueY:1;
//            if((trueX+trueWidth)>=videoWidth){
//                trueWidth = videoWidth-trueX-1;
//            }
//            if((trueY+trueHeight)>videoHeight){
//                trueHeight = videoHeight-trueY-1;
//            }
            mProgressDialog = new ProgressDialog(this);
            mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            mProgressDialog.setMax(100);
            mProgressDialog.setCancelable(false);
            mProgressDialog.setCanceledOnTouchOutside(false);
            mProgressDialog.setTitle("正在处理");

            mProgressDialog.show();
            //去水印ffmpeg -i logo.mp4 -filter_complex "delogo=x=100:y=100:w=100:h=100:show=1" delogo.mp4
            out = VideoUtil.VIDEO_SLIDE_DIR + "/" + System.currentTimeMillis() + ".mp4";
            //show=1 绿色边框
            //-i 1.jpg -vf "movie=2.jpg,scale=150:183[watermask];[in][watermask] overlay=100:100[out]" -y 3.jpg
//            String cmd = String.format("-i %s -filter_complex delogo=x=%s:y=%s:w=%s:h=%s:show=0 %s", path, trueX+"", trueY+"", trueWidth+"", trueHeight+"", out);
//            String cmd = String.format("-i %s -filter_complex delogo=x=%s:y=%s:w=%s:h=%s: %s", path, trueX+"", trueY+"", trueWidth+"", trueHeight+"", out);
//            int duration = VideoUtil.getDuration(this, path);
//            Log.d(TAG, "duration "+duration);
//            Log.d(TAG, "cmd "+cmd);
            //FFmpeg修改
//            EpEditor.execCmd(cmd, duration*1000, new OnEditorListener() {
//                @Override
//                public void onSuccess() {
//                    mHandler.sendEmptyMessage(MSG_SUCCESS);
//                }
//
//                @Override
//                public void onFailure() {
//                    mHandler.sendEmptyMessage(MSG_FAIL);
//                }
//
//                @Override
//                public void onProgress(float progress) {
//                    Message msg = new Message();
//                    Bundle data = new Bundle();
//                    data.putFloat("progress", progress);
//                    msg.setData(data);
//                    msg.what = MSG_PROGRESS;
//                    mHandler.sendMessage(msg);
////                    mProgressDialog.setProgress((int) (progress * 100));
//                }
//            });
        }
    }


    public static final int MSG_SUCCESS = 101;
    public static final int MSG_FAIL = 102;
    public static final int MSG_PROGRESS = 103;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == MSG_SUCCESS) {
                Log.i("视频去水印", "视频剪切");
                Toast.makeText(VideoSpliceActivity.this, "处理完成", Toast.LENGTH_SHORT).show();
                MyArt art = new MyArt();
                art.setHeight(videoHeight);
                art.setWidth(videoWidth);
                art.setCreate_time(System.currentTimeMillis() + "");
                art.setPath(out);
                art.setType(1);
                art.save();
                if (mProgressDialog.isShowing()) {
                    mProgressDialog.dismiss();
                }
//                FileUtil.ablumUpdate(VideoSpliceActivity.this, art.getPath(),1);//更新相册
                Intent intent = new Intent(VideoSpliceActivity.this, ShowMyArtsActivity.class);
                intent.putExtra(EXTRA_OUTPUT, out);
                intent.putExtra("create_time", art.getTrueCreateTime());
                intent.putExtra("width", videoWidth);
                intent.putExtra("height", videoHeight);
                intent.putExtra("type", "1");
                startActivity(intent);
                finish();

            } else if (msg.what == MSG_FAIL) {
                Toast.makeText(VideoSpliceActivity.this, "处理失败", Toast.LENGTH_SHORT).show();
                if (mProgressDialog.isShowing()) {
                    mProgressDialog.dismiss();
                }
            } else if (msg.what == MSG_PROGRESS) {
                float progress = msg.getData().getFloat("progress");
                mProgressDialog.setProgress((int) (progress));
            }
        }
    };

    @Override
    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart("VideoSpliceActivity");//统计页面
        MobclickAgent.onResume(this);
    }
    @Override
    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd("VideoSpliceActivity");//统计页面
        MobclickAgent.onPause(this);
    }
}
